﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Web;
using Twipler.App;
using Twipler.App.Session;

namespace Twipler.WebApp
{
    public class ExceptionReport
    {
        public static void Report(Exception ex)
        {
            Current.Log.Fatal("* exception *");
            Current.Log.Fatal(CreateReport(ex));
        }

        private static string CreateReport(Exception ex)
        {
            try
            {
                StringBuilder html = new StringBuilder();

                html.AppendFormat("Exception: {0}\r", ex.Message);

                int indent = 0;
                while (ex.InnerException != null)
                {
                    indent++;

                    for (int i = 0; i < indent; i++)
                        html.Append("  ");

                    ex = ex.InnerException;
                    html.AppendFormat("Exception: {0}\r", ex.Message);
                }

                html.Append("\rStack\r");
                html.Append(ex.StackTrace);

                html.AppendFormat("Request: {0}\r", System.Web.HttpContext.Current.Request.RawUrl);

                if (System.Web.HttpContext.Current == null)
                    html.Append("- no http context -");
                else
                {
                    
                    html.Append("\nApplication\n");
                    foreach (string key in HttpContext.Current.Application.Keys)
                        html.AppendFormat(" {0}: {1}\n", key, HttpContext.Current.Application[key]);

                    if (HttpContext.Current.Session == null)
                    {
                        html.AppendFormat("- no session\r");
                    }
                    else
                    {

                        html.Append("\nSession\n");
                        foreach (string key in HttpContext.Current.Session.Keys)
                        {
                            if (key != "SessionTrack")
                                html.AppendFormat(" {0}: {1}\n", key, System.Web.HttpContext.Current.Session[key]);
                        }
                    }

                    
                }

                return html.ToString();
            }
            catch (Exception exception)
            {
                return "Exception while creating exception report! " + exception.Message;
            }
        }
    }
}
